package com.ming.demo.easyiot;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.hardware.usb.UsbManager;
import android.location.Location;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Projection;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;
import okhttp3.Call;
import okhttp3.MediaType;

import static android.R.attr.elegantTextHeight;
import static android.R.attr.id;
import static android.R.attr.min;
import static android.R.id.list;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static android.os.Build.VERSION_CODES.M;
import static com.amap.api.mapcore2d.p.i;
import static com.baidu.location.g.j.S;
import static com.google.gson.internal.UnsafeAllocator.create;
import static com.loc.e.b;
import static com.loc.e.m;
import static com.ming.demo.easyiot.R.id.mFlMap;
import static com.ming.demo.easyiot.R.id.mTvLat;
import static com.ming.demo.easyiot.R.id.mTvLon;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String Connect = "\r\nCONNECTDEV\r\n";
    //    public static final String Connect = "AT\r\n";
    public static final String Query = "\r\nQUERYNBINFO\r\n";
    public static final String CloseLog = "\r\nDEBUGLEVEL:0\r\n";
    public static final String SetBand = "AT+NBAND=5\r\n";
    public static final String GetBand = "AT+NBAND?\r\n";
    public static final String GetApplication = "AT+CGMR\r\n";
    public static final String GetImei = "AT+CGSN=1\r\n";
    public static final String GetImsi = "AT+CIMI\r\n";
    public static final String GetCfun = "AT+CFUN?\r\n";
    public static final String GetCgat = "AT+CGATT?\r\n";
    public static final String GetAddress = "AT+NCDP?\r\n";
    public static final String GetApn = "AT+CGDCONT?\r\n";
    public static final String GetIp = "AT+CGPADDR\r\n";
    public static final String GetPlaceInfo = "AT+NUESTATS\r\n";
    public static final String ResetAddress = "AT+NCDP= 117.60.157.137,5683\r\n";
    public static final String ReRun = "AT+NRB\r\n";
    public static final String Ping = "AT+NPING=180.101.147.115\r\n";
    public static final String Regist = "AT+NMGS=1,01\r\n";
    public static String GPS = "\r\nGPSINFO:|N|｜E|\r\n";
    public static final String TAG = "cn.wch.wchusbdriver";
    //    public static final String Connect = "ATE1\r\n";
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    public readThread handlerThread;
    protected final Object ThreadLock = new Object();
    private boolean isOpen;
    private boolean isAuto = false;
    private boolean isSetCYCLE = false, isGetLocation = true;
    private int retval;
    private MainActivity activity;
    public byte[] writeBuffer;
    public byte[] readBuffer;
    public int baudRate;
    public byte baudRate_byte;
    public byte stopBit;
    public byte dataBit;
    public byte parity;
    public byte flowControl;
    public int pingCount = 0;
    public int state = -1;//(MCU) 0 connect  1 query   (OTHER) 0 connect 1 setBand 2~8 query
    public int isMcu101 = 0;//0 yes 1 no
    public String queryType = "";
    public int queryFlag = 0;
    public String curStr = "";
    public String queryInfo = "";
    public String queryInfoList[];
    public String CellID = "", PCI = "", EARFCN = "", PositionRemark = "", ModelVersion = "", Altitude = "", PositionCoordinates, autoAddress, PositionCoordinates2, IMEI = "", IMSI = "", APN = "", IPAddress = "";
    public float SNR = 0;
    public Long TimeStamp;
    public int RSRP, RSSI, TXPower, ReportType, UEType = -1, CFUN = 1, CGAT = 1, BAND;
    public TextView mTvState, mTvId, mTvXinZao, mTvDb, mTvDate, mTvHistory, mTvUpdate, mTvRight, mTvCellId, mTvAddress;
    public ImageView mIvGetLocation;
    public LinearLayout mLyAutoReport, mLyOnceReport, mLyPing;
    public ImageView mIvLink, mIvBegin;
    //    private AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public int update_time = 10000;//上传间隔
    public int cycle_time = 60;
    private RadioGroup mRgTime;
    Handler ClockHandler;
    JSONObject PingReturnedValue = new JSONObject();
    JSONObject PingReturnedValue2 = new JSONObject();
    String totalping = "";
    PostUtil post;
    private UpdateUtil updateUtil;
    private String versionCode;   //版本号
    private String ApKURL; //下载apk地址
    private String version_description;//更新描述
    String lastReturn = "";
    private long exitTime = 0;
    private ImageView mIvAbout;
    private int lastId = R.id.mRb2Time3;
    private EditText mEtNote;
    int isDrag = 0;
    boolean isFirst = true;
    private ServiceInfo lastInfo;
    private LinearLayout mLyDetail;
    public LocationClient mLocationClient = null;
    public StateUtil stateUtil;
    public int mistake = -1;
    TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    GeoCoder geoCoder, geoCoder2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        geoCoder = GeoCoder.newInstance();
        geoCoder2 = GeoCoder.newInstance();
        setContentView(R.layout.activity_main);
        stateUtil = new StateUtil(this);
        initUI();
        updata();
        MyApp.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        if (!MyApp.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST
        {
            Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持常亮的屏幕的状态
        writeBuffer = new byte[512];
        readBuffer = new byte[512];
        isOpen = false;
        activity = this;
        open();
//        Timehandler.postDelayed(TimeRunnable, update_time);


    }

    //解析处理数据
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            String returnResult = (String) msg.obj;
            curStr = curStr + returnResult;
            if (curStr.indexOf("REBOOT_CAUSE") != -1) {
                if (!isFirst)
                    Toast.makeText(MainActivity.this, "侦测到NB模组已重启，正在重新连接中", Toast.LENGTH_SHORT).show();
                CountDownTimer timer = new CountDownTimer(3 * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onFinish() {
                        isFirst = true;
                        state = StateUtil.CONNECT;
                        write(Connect);
                    }
                }.start();
            }
            switch (state) {
                case StateUtil.CONNECT:
                    if (curStr.indexOf("MCU") != -1) {
//                        getLocation();
                        UEType = Integer.parseInt(mySplit("MCU", curStr).split(":")[1]);
                        if (UEType == 101) {
                            isMcu101 = 0;
                            curStr = "";
                            if (isFirst) {
                                Toast.makeText(MainActivity.this, "初始化结束", Toast.LENGTH_SHORT).show();
                                state = -1;
                                isFirst = false;
                            } else {
                                if (isSetCYCLE == false) {
                                    curStr = "";
                                    stateUtil.set101Command();
                                    state = stateUtil.getNextState();
                                    write(stateUtil.getNextCommand());
                                } else {
                                    curStr = "";
                                    state = StateUtil.CYCLE;
                                    write("\r\nSETCYCLE:" + cycle_time + "\r\n");
                                }
                            }

                        } else if (UEType == 102) {
                            isMcu101 = 1;
                            curStr = "";
                            if (isFirst) {
                                stateUtil.AddList(GetImei, StateUtil.IMEI);
                                stateUtil.AddList(GetApplication, StateUtil.APPLICATION);
                                stateUtil.AddList(GetBand, StateUtil.BAND);
                                stateUtil.AddList(GetImsi, StateUtil.IMSI);
                                stateUtil.AddList(GetCfun, StateUtil.CFUN);
                                stateUtil.AddList(GetCgat, StateUtil.CGAT);
                                state = stateUtil.getNextState();
                                write(stateUtil.getNextCommand());
                            } else {
                                if (isSetCYCLE == false) {
                                    stateUtil.set102Command();
                                    state = stateUtil.getNextState();
                                    write(stateUtil.getNextCommand());
                                } else {
                                    state = -1;
                                    isSetCYCLE = false;
                                    Toast.makeText(MainActivity.this, "设置失败！这不是一个NS101设备！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else {
                            state = -1;
                            curStr = "";
                            Toast.makeText(MainActivity.this, "同步失败！这不是一个合法的设备！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    if (curStr.indexOf("ERROR\r\n") != -1) {
                        curStr = "";
                        state = -1;
                        if (isFirst) {
                            Toast.makeText(MainActivity.this, "初始化失败！请点击上报按钮重新初始化！", Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(MainActivity.this, "获取信息失败！请重新上报！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case StateUtil.QUERY101:
                    if (returnResult.indexOf("\r\n") != -1) {
                        queryFlag = 1 - queryFlag;
                    }
                    if (queryFlag == 0) {
                        queryInfoList = curStr.split("\\|");
                        try {
                            ModelVersion = queryInfoList[0].split(":")[1];
                            IMEI = queryInfoList[1];
                            if (!IMEI.equals("null")) {
                                mTvId.setText("设备编号(IMEI)：" + queryInfoList[1]);
                            }
                            IMSI = queryInfoList[2];
                            APN = queryInfoList[5];
                            IPAddress = queryInfoList[6];
                            EARFCN = queryInfoList[7];
                            CellID = queryInfoList[8];
                            mTvCellId.setText(CellID);
                            PCI = queryInfoList[9];
                            RSRP = Integer.parseInt(queryInfoList[10]);
                            mTvDb.setText(RSRP + "dBm");
                            RSSI = Integer.parseInt(queryInfoList[11]);
                            TXPower = Integer.parseInt(queryInfoList[12]);
                            SNR = Float.parseFloat(queryInfoList[13]);
                            mTvXinZao.setText(SNR + "");
                        } catch (Exception ex) {

                        }
                        try {
                            CFUN = Integer.parseInt(queryInfoList[15]);
                            CGAT = Integer.parseInt(queryInfoList[16]);
                        } catch (Exception ex) {

                        }
                        curStr = "";
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    }
                    break;
                case StateUtil.GPS:
                    if (curStr.indexOf("GPSINFORSP\r\n") != -1) {
                        if (ReportType != 2) {
                            state = -1;
                            postInfo();
                        } else {
                            PingReturnedValue = new JSONObject();
                            PingReturnedValue2 = new JSONObject();
                            state = StateUtil.PING;
                            write(Ping);
                        }
                    } else {
                        state = -1;
                        postInfo();
                    }
                    break;
                case StateUtil.BAND:
                    if (curStr.indexOf("OK\r\n") != -1) {
                        BAND = Integer.parseInt(mySplit("NBAND", curStr).split(":")[1]);
                        curStr = "";
                        if (BAND == 5) {
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        } else {
                            Toast.makeText(MainActivity.this, "当前NB模组频段值为" + BAND + "，设置不正确", Toast.LENGTH_SHORT).show();
                            mistake = StateUtil.BAND;
                            state = -1;
                        }
                    }
                    break;
                case StateUtil.IMEI:
                    if (curStr.indexOf("ERROR\r\n") != -1) {
                        curStr = "";
                        timeoutCount = 5;
                        if (count == 0)
                            TimeOutthandler.postDelayed(TimeOutRunnable, 500);
                        if (count < 5) {
                            state = StateUtil.IMEI;
                            write(GetImei);
                        } else {
                            Toast.makeText(MainActivity.this, "查询不到IMEI", Toast.LENGTH_SHORT).show();
                            mistake = StateUtil.IMEI;
                            state = -1;
                        }
                    } else if (curStr.indexOf("OK\r\n") != -1) {
                        count = 0;
//                        Toast.makeText(MainActivity.this, curStr, Toast.LENGTH_LONG).show();
                        IMEI = mySplit("CGSN", curStr).split(":")[1];
                        mTvId.setText("设备编号(IMEI)：" + IMEI);
                        curStr = "";
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    }
                    break;
                case StateUtil.APPLICATION:
                    if (curStr.indexOf("ERROR\r\n") != -1) {
                        curStr = "";
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    } else {
                        if (curStr.indexOf("OK\r\n") != -1) {
                            ModelVersion = mySplit("APPLICATION", curStr);
                            ModelVersion = ModelVersion.split(",")[1];
                            curStr = "";
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        }
                    }
                    break;
                case StateUtil.IMSI:
                    if (curStr.indexOf("ERROR\r\n") != -1) {
                        curStr = "";
                        timeoutCount = 5;
                        if (count == 0)
                            TimeOutthandler.postDelayed(TimeOutRunnable, 500);
                        if (count < 5) {
                            state = StateUtil.IMSI;
                            write(GetImsi);
                        } else {
                            Toast.makeText(MainActivity.this, "查询不到IMSI", Toast.LENGTH_SHORT).show();
                            mistake = StateUtil.IMSI;
                            state = -1;
                        }
                    } else if (returnResult.indexOf("OK\r\n") != -1) {
                        count = 0;
                        IMSI = mySplit("460", curStr);
                        curStr = "";
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    }
                    break;
                case StateUtil.CFUN:
                    if (curStr.indexOf("OK\r\n") != -1) {
                        CFUN = Integer.parseInt(mySplit("CFUN", curStr).split(":")[1]);
                        curStr = "";
                        if (CFUN == 0) {
                            curStr = "";
                            timeoutCount = 10;
                            if (count == 0)
                                TimeOutthandler.postDelayed(TimeOutRunnable, 500);
                            if (count < 10) {
                                state = StateUtil.CFUN;
                                write(GetCfun);
                            } else {
                                Toast.makeText(MainActivity.this, "NB模组未能使用", Toast.LENGTH_SHORT).show();
                                mistake = StateUtil.CFUN;
                                state = -1;
                            }
                        } else {
                            count = 0;
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        }
                    }
                    break;
                case StateUtil.CGAT:
                    if (curStr.indexOf("OK\r\n") != -1) {
                        CGAT = Integer.parseInt(mySplit("CGATT", curStr).split(":")[1]);
                        curStr = "";
                        isFirst = false;
                        if (CGAT == 0) {
                            curStr = "";
                            timeoutCount = 30;
                            if (count == 0)
                                TimeOutthandler.postDelayed(TimeOutRunnable, 500);
                            if (count < 30) {
                                state = StateUtil.CGAT;
                                write(GetCgat);
                            } else {
                                Toast.makeText(MainActivity.this, "网络未附着", Toast.LENGTH_SHORT).show();
                                state = -1;
                            }
                        } else {
                            state = -1;
                            Toast.makeText(MainActivity.this, "初始化结束", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case StateUtil.APN:
                    if (curStr.indexOf(",,,") != -1) {
                        if (curStr.indexOf("OK\r\n") != -1) {
                            try {
                                APN = curStr.split(",")[2];
                                APN = APN.substring(1, APN.length() - 1);
                            } catch (Exception ex) {
                                APN = "";
                            }
                            curStr = "";
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        }
                    } else {
                        if (curStr.indexOf("OK\r\n") != -1) {
                            try {
                                APN = curStr.split(",")[2];
                                APN = APN.substring(1, APN.length() - 1);
                            } catch (Exception ex) {
                                APN = "";
                            }
                            curStr = "";
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        }
                    }
                    break;
                case StateUtil.IPADDRESS:
                    if (curStr.indexOf("CGPADDR:0\r") != -1) {
                        if (curStr.indexOf("OK\r\n") != -1) {
                            IPAddress = "";
                            curStr = "";
                            state = stateUtil.getNextState();
                            write(stateUtil.getNextCommand());
                        }
                    } else {
                        if (curStr.indexOf("CGPADDR:0,") != -1) {
                            if (curStr.indexOf("OK\r\n") != -1) {
                                IPAddress = mySplit("CGPADDR", curStr);
                                IPAddress = IPAddress.split(",")[1];
                                curStr = "";
                                state = stateUtil.getNextState();
                                write(stateUtil.getNextCommand());
                            }
                        }
                    }
                    break;
                case StateUtil.QUERY102:
                    if (returnResult.indexOf("ERROR\r\n") != -1) {
                        curStr = "";
                        CellID = "";
                        SNR = 0;
                        PCI = "";
                        RSRP = 0;
                        RSSI = 0;
                        EARFCN = "";
                        TXPower = 0;
                        mTvDb.setText("0dBm");
                        mTvXinZao.setText("0");
                        if (ReportType != 2) {
                            state = -1;
                            postInfo();
                        } else {
                            state = 11;
                            PingReturnedValue = new JSONObject();
                            PingReturnedValue2 = new JSONObject();
                            write(Ping);
                        }

                    } else if (curStr.indexOf("OK\r\n") != -1) {
                        CellID = StrdecodeDate2("Cell", curStr);
                        mTvCellId.setText(CellID);
                        SNR = FloatdecodeDate("SNR", curStr);
                        PCI = StrdecodeDate2("PCI", curStr);
                        RSRP = IntdecodeDate("Signal power", curStr);
                        RSSI = IntdecodeDate("Total", curStr);
                        EARFCN = StrdecodeDate2("EARFCN", curStr);
                        TXPower = IntdecodeDate("TX power", curStr);
                        mTvDb.setText(RSRP + "dBm");
                        mTvXinZao.setText(SNR + "");
                        curStr = "";
                        if (ReportType != 2) {
                            state = -1;
                            postInfo();
                        } else {
                            state = StateUtil.PING;
                            PingReturnedValue = new JSONObject();
                            PingReturnedValue2 = new JSONObject();
                            write(Ping);
                        }
                    }
                    break;
                case StateUtil.CYCLE:
                    if (isSetCYCLE == true) {
                        if (curStr.indexOf("SETCYCLERSP\r\n") != -1) {
                            state = -1;
                            isSetCYCLE = false;
                            curStr = "";
                            Toast.makeText(MainActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        state = -1;
                        curStr = "";
                    }
                    break;
                case StateUtil.PING:
                    if (curStr.indexOf("ERROR") != -1) {
                        pingCount++;
                        try {
                            PingReturnedValue.put("" + pingCount, "null");
                            PingReturnedValue2.put("第" + pingCount + "次", "超时");
                            totalping = totalping + "第" + pingCount + "次ping超时" + "\n";
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        curStr = "";
                        if (pingCount < 5) {
                            Toast.makeText(MainActivity.this, "第" + pingCount + "次延迟时间：超时", Toast.LENGTH_SHORT).show();
                            write(Ping);
                        } else {
                            pingCount = 0;
                            state = -1;
                            pingDialog(PingReturnedValue2.toString());
//                            Toast.makeText(MainActivity.this, "所有延迟时间：" + PingReturnedValue2.toString(), Toast.LENGTH_LONG).show();
                            postInfo();
                            if (isAuto) {
                                Timehandler.postDelayed(TimeRunnable, update_time);
                            }
                        }
                    }
                    if (curStr.indexOf("NPINGERR:1\r\n") != -1) {
                        pingCount++;
                        try {
                            PingReturnedValue.put("" + pingCount, "null");
                            PingReturnedValue2.put("第" + pingCount + "次", "超时");
                            totalping = totalping + "第" + pingCount + "次ping超时" + "\n";
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        curStr = "";
                        if (pingCount < 5) {
                            Toast.makeText(MainActivity.this, "第" + pingCount + "次延迟时间：超时", Toast.LENGTH_SHORT).show();
                            write(Ping);
                        } else {
                            pingCount = 0;
                            state = -1;
                            pingDialog(PingReturnedValue2.toString());
//                            Toast.makeText(MainActivity.this, "所有延迟时间：" + PingReturnedValue2.toString(), Toast.LENGTH_LONG).show();
                            postInfo();
                            if (isAuto) {
                                Timehandler.postDelayed(TimeRunnable, update_time);
                            }
                        }
                    } else if (curStr.indexOf("NPING:") != -1 && curStr.split(",").length > 2) {
                        pingCount++;
                        try {
                            curStr = mySplit("NPING:", curStr);
                            Toast.makeText(MainActivity.this, "第" + pingCount + "次延迟时间：" + curStr.split(",")[2], Toast.LENGTH_SHORT).show();
                            PingReturnedValue.put("" + pingCount, curStr.split(":")[1]);
                            PingReturnedValue2.put("第" + pingCount + "次", curStr.split(":")[1]);
                            totalping = totalping + "第" + pingCount + "次ping" + curStr.split(":")[1] + "\n";

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        curStr = "";
                        if (pingCount < 5) {
                            write(Ping);
                        } else {
                            pingCount = 0;
                            state = -1;
                            pingDialog(totalping);
                            totalping = "";
//                            Toast.makeText(MainActivity.this, "所有延迟时间：" + PingReturnedValue2.toString(), Toast.LENGTH_LONG).show();
                            postInfo();
                            if (isAuto) {
                                Timehandler.postDelayed(TimeRunnable, update_time);
                            }
                        }
                    }

                    break;
            }
        }
    };

    //打开设备
    public void open() {
        retval = MyApp.driver.ResumeUsbList();
        if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
        {
            Toast.makeText(MainActivity.this, "打开设备失败!",
                    Toast.LENGTH_SHORT).show();
            mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.begin));
            Timehandler.removeCallbacks(TimeRunnable);
            MyApp.driver.CloseDevice();
        } else if (retval == 0) {
            if (!MyApp.driver.UartInit()) {//对串口设备进行初始化操作
                Toast.makeText(MainActivity.this, "设备初始化失败!",
                        Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, "打开" +
                                "设备失败!",
                        Toast.LENGTH_SHORT).show();
                mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.begin));
                Timehandler.removeCallbacks(TimeRunnable);
                return;
            }
//            Toast.makeText(MainActivity.this, "打开设备成功!",
//                    Toast.LENGTH_SHORT).show();
            isOpen = true;
            config();
            new readThread().start();//开启读线程读取串口接收的数据
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setIcon(R.drawable.icon);
            builder.setTitle("未授权限,请拔下usb重连获取权限");
            builder.setMessage("确认退出吗？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
//								MainFragmentActivity.this.finish();
                    System.exit(0);
                }
            });
            builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
            builder.show();

        }
    }

    public void config() {
        baudRate = 9600;
        dataBit = 8;
        stopBit = 1;
        parity = 0;
        flowControl = 0;
        if (MyApp.driver.SetConfig(baudRate, dataBit, stopBit, parity,//配置串口波特率，函数说明可参照编程手册
                flowControl)) {
//            Toast.makeText(MainActivity.this, "串口设置成功!",
//                    Toast.LENGTH_SHORT).show();
            state = -1;
//            write(Connect);
            write(CloseLog);
            if (ReportType == 1) {
                isAuto = true;
            }
            mIvLink.setImageDrawable(getResources().getDrawable(R.drawable.already_link));
            ReConnecthandler.removeCallbacks(ReConnectRunnable);
            mTvState.setText("已连接");
            isFirst = true;
            state = StateUtil.CONNECT;
            CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onFinish() {
                    write(Connect);
                    ReConnecthandler.postDelayed(ReConnectRunnable, 5000);
                }
            }.start();


        } else {
            Timehandler.removeCallbacks(TimeRunnable);
            Toast.makeText(MainActivity.this, "串口设置失败!",
                    Toast.LENGTH_SHORT).show();
            mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.begin));
        }
    }

    public void write(String msg) {
        byte[] to_send = msg.getBytes(StandardCharsets.US_ASCII);
        int retval = MyApp.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
        if (retval < 0) {
            state = -1;
            Toast.makeText(MainActivity.this, "写失败!",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {
//        if (lastReturn.equals("")) {
//            state = -1;
//        }
        switch (view.getId()) {
            case R.id.mLyAutoReport:
                if (isAuto == true) {
                    isAuto = false;
                    Timehandler.removeCallbacks(TimeRunnable);
                    mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.begin));
                    state = -1;
//                    resetUI();
                } else {
                    if (!isUsed()) {
                        break;
                    }
                    ReportType = 1;
                    mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.pause));
                    if (MyApp.driver.isConnected()) {
                        isAuto = true;
                        stateUtil.setCommand();
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    } else {
                        Toast.makeText(MainActivity.this, "正在重连", Toast.LENGTH_SHORT).show();
                        open();
                    }
                    Timehandler.postDelayed(TimeRunnable, update_time);
                }
                break;
            case R.id.mLyOnceReport:
                if (!isUsed()) {
                    break;
                }
                Toast.makeText(this, "正在开始检测信号！", Toast.LENGTH_SHORT).show();
                ReportType = 0;
                if (MyApp.driver.isConnected()) {
                    if (isAuto) {//若处于自动上报状态，暂停线程进行手动上报，完毕以后再进行自动上报
                        Timehandler.removeCallbacks(TimeRunnable);
                        stateUtil.setCommand();
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                        Timehandler.postDelayed(TimeRunnable, update_time);
                    } else {
                        stateUtil.setCommand();
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    }
                } else {
                    Toast.makeText(MainActivity.this, "正在重连", Toast.LENGTH_SHORT).show();
                    open();
                }
                break;
            case R.id.mLyPing:
                if (!isUsed()) {
                    break;
                }
                Toast.makeText(this, "正在开始PING！", Toast.LENGTH_SHORT).show();
                ReportType = 2;
                if (MyApp.driver.isConnected()) {
                    if (isAuto) {//若处于自动上报状态，暂停线程进行手动上报，完毕以后再进行自动上报
                        Timehandler.removeCallbacks(TimeRunnable);
                        stateUtil.setCommand();
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
//                    Timehandler.postDelayed(TimeRunnable, update_time); //在ping完毕以后重启
                    } else {
                        stateUtil.setCommand();
                        state = stateUtil.getNextState();
                        write(stateUtil.getNextCommand());
                    }
                } else {
                    Toast.makeText(MainActivity.this, "正在重连", Toast.LENGTH_SHORT).show();
                    open();
                }

                break;
            case R.id.mTvRight:
                Intent intent = new Intent();
                intent.setClass(this, HistoryActivity.class);
                startActivity(intent);
                break;
            case R.id.about:
//                getLocation();
                showAboutDialog();
                break;
            case R.id.mLyDetail:
                showDetailDialog();
                break;
            case R.id.mIvGetLocation:
                isGetLocation = true;
                getLocation();
                break;
        }
    }

    public boolean isUsed() {
        if (mistake != -1)
            if (UEType == 102) {
                if (mistake == StateUtil.BAND) {
                    Toast.makeText(MainActivity.this, "当前NB模组频段值为" + BAND + "，设置不正确", Toast.LENGTH_SHORT).show();
                    return false;
                }
                if (mistake == StateUtil.IMEI) {
                    Toast.makeText(MainActivity.this, "查询不到IMEI", Toast.LENGTH_SHORT).show();
                    return false;
                }
                if (mistake == StateUtil.IMSI) {
                    Toast.makeText(MainActivity.this, "查询不到IMSI", Toast.LENGTH_SHORT).show();
                    return false;
                }
                if (mistake == StateUtil.CFUN) {
                    Toast.makeText(MainActivity.this, "NB模组未能使用", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }


        if (state != -1) {
            Toast.makeText(this, "请稍后再点击！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void resetUI() {
//        MyApp.driver.CloseDevice();
        isFirst = true;
        mTvDb.setText("0dBm");
        mTvXinZao.setText("0");
        mTvId.setText("设备编号：(15位数字)");
//        mTvState.setText("未连接");
//        mIvLink.setImageDrawable(getResources().getDrawable(R.drawable.no_link));
        mIvBegin.setImageDrawable(getResources().getDrawable(R.drawable.begin));
        state = -1;
//        isOpen = false;
    }

    private class readThread extends Thread {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        public void run() {
            while (true) {
                byte[] buffer = new byte[32];
                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = MyApp.driver.ReadData(buffer, 32);
                if (length > 0) {
//                    String recv = toHexString(buffer, length);
                    String recv = new String(buffer, StandardCharsets.US_ASCII);
                    msg.obj = recv;
                    handler.sendMessage(msg);
                }
            }
        }
    }


    public void initUI() {
//        FrameLayout mFlMap = (FrameLayout) findViewById(R.id.mFlMap);
//        WindowManager wm = (WindowManager) MainActivity.this
//                .getSystemService(Context.WINDOW_SERVICE);
//        int width = wm.getDefaultDisplay().getWidth();
//        int height = wm.getDefaultDisplay().getHeight();
//
//        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mFlMap.getLayoutParams();
//        lp.height = height / 5 * 3;
//        mFlMap.setLayoutParams(lp);
////        ScaleUtil.ScaleUtil(mFlMap, MainActivity.this, (LinearLayout.LayoutParams) mFlMap.getLayoutParams(), 3, 2);
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        MainActivity.this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mFlMap.getLayoutParams();
//        params.height = displayMetrics.heightPixels / 5 * 3;
//        mFlMap.setLayoutParams(params);
        mMapView = (TextureMapView) findViewById(R.id.mTexturemap);
        mMapView.showZoomControls(false);
//        mMapView.showScaleControl(false);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);
        MapStatusUpdate update = MapStatusUpdateFactory.zoomTo(20f);
        mBaiduMap.animateMapStatus(update);
        mIvGetLocation = (ImageView) findViewById(R.id.mIvGetLocation);
        mIvGetLocation.setOnClickListener(this);
        mTvAddress = (TextView) findViewById(R.id.mTvAddress);
        mTvCellId = (TextView) findViewById(R.id.mTvCellId);
        mEtNote = (EditText) findViewById(R.id.mEtNote);
        mTvState = (TextView) findViewById(R.id.mTvState);
        mTvId = (TextView) findViewById(R.id.mTvId);
        mTvDb = (TextView) findViewById(R.id.mTvDb);
        mTvXinZao = (TextView) findViewById(R.id.mTvXinZao);
        mTvHistory = (TextView) findViewById(R.id.mTvHistory);
        mTvUpdate = (TextView) findViewById(R.id.mTvUpdate);
        mIvLink = (ImageView) findViewById(R.id.mIvLink);
        mIvBegin = (ImageView) findViewById(R.id.mIvBegin);
        mTvRight = (TextView) findViewById(R.id.mTvRight);
        mTvRight.setOnClickListener(this);
        mIvAbout = (ImageView) findViewById(R.id.about);
        mIvAbout.setOnClickListener(this);
        mLyAutoReport = (LinearLayout) findViewById(R.id.mLyAutoReport);
        mLyOnceReport = (LinearLayout) findViewById(R.id.mLyOnceReport);
        mLyPing = (LinearLayout) findViewById(R.id.mLyPing);
        mLyPing.setOnClickListener(this);
        mLyOnceReport.setOnClickListener(this);
        mLyAutoReport.setOnClickListener(this);
        mLyDetail = (LinearLayout) findViewById(R.id.mLyDetail);
        mLyDetail.setOnClickListener(this);
        mRgTime = (RadioGroup) findViewById(R.id.mRgTime);
        mRgTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                switch (id) {
                    case R.id.mRbTime1:
                        update_time = 10000;
                        break;
                    case R.id.mRbTime2:
                        update_time = 30000;
                        break;
                    case R.id.mRbTime3:
                        update_time = 60000;
                        break;
                    case R.id.mRbTime4:
                        update_time = 300000;
                        break;
                    case R.id.mRbTime5:
                        update_time = 600000;
                        break;
                }
            }
        });
        post = new PostUtil(this);
        SQLiteDatabase db = LitePal.getDatabase();
//        List<ServiceInfo> infoList = DataSupport.findAll(ServiceInfo.class);
//        Toast.makeText(this,infoList.toString(),Toast.LENGTH_LONG).show();
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(mListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标
        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true
        option.setLocationNotify(true);
        option.setScanSpan(2000);

        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false
        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setIsNeedAltitude(true);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位
        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false
        mLocationClient.setLocOption(option);
        getLocation();

    }


    public void getLocation() {
        if (Build.VERSION.SDK_INT >= M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationClient.restart();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        1001);//自定义的code
            }
        } else {
            mLocationClient.restart();
        }
    }


    //定时上传
    Handler Timehandler = new Handler();
    Runnable TimeRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情
            if (state == -1) {
                ReportType = 1;
                stateUtil.setCommand();
                state = stateUtil.getNextState();
                write(stateUtil.getNextCommand());
//            Toast.makeText(MainActivity.this, "time" + update_time, Toast.LENGTH_LONG).show();
                Timehandler.postDelayed(this, update_time);
            } else {
                Timehandler.postDelayed(this, 1000);
            }
        }
    };
    int count = 0;
    int timeoutCount = 5;
    Handler TimeOutthandler = new Handler();
    Runnable TimeOutRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情
            count++;
            if (count < timeoutCount)
                TimeOutthandler.postDelayed(this, 1000);
            else {
                TimeOutthandler.removeCallbacks(TimeOutRunnable);
            }
        }
    };

    Handler ReConnecthandler = new Handler();
    Runnable ReConnectRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情
            if (state == 0) {
                config();
                Toast.makeText(MainActivity.this, "正在重连", Toast.LENGTH_SHORT).show();
                ReConnecthandler.postDelayed(this, 5000);
            } else {
                ReConnecthandler.removeCallbacks(ReConnectRunnable);
            }
        }
    };

    public String mySplit(String key, String str) {
        String[] list = str.split(key);
        if (list.length <= 1)
            return "";
        str = key + list[1].split("\\r")[0];
        return str;
    }

    public int IntdecodeDate(String key, String Date) {
        String str = mySplit(key, Date);
//        return 0;
        try {
            int num = Integer.parseInt(str.split(":")[1]);

            if (num < -1000 || num > 30000) {
                return num / 10;
            } else {
                return num / 10;
            }
        } catch (Exception ex) {
            return 0;
        }
    }

    public float FloatdecodeDate(String key, String Date) {
        String str = mySplit(key, Date);
//        return 0;
        try {
            float num = Integer.parseInt(str.split(":")[1]);
//            Toast.makeText(MainActivity.this,num+"",Toast.LENGTH_SHORT).show();
            if (num < -1000 || num > 30000) {
                return num / 10;
            } else {
                return num / 10;
            }
        } catch (Exception ex) {
            return 0;
        }
    }

    public String StrdecodeDate(String key, String Date) {
        String str = mySplit(key, Date);
//        return str;
        try {
            int num = Integer.parseInt(str.split(":")[1]);

            if (num < -1000 || num > 30000) {
                return num / 10 + "";
            } else {
                return num / 10 + "";
            }
        } catch (Exception ex) {
            return "0";
        }
    }

    public String StrdecodeDate2(String key, String Date) {
        String str = mySplit(key, Date);
        try {
            if (str.split(":")[1].equals("0")) {
                return "";
            } else {
                return str.split(":")[1];
            }
        } catch (Exception ex) {
            return "0";
        }

    }


    public void postInfo() {

        ServiceInfo info = new ServiceInfo();
        info.setIMEI(IMEI);//0
        info.setIMSI(IMSI);//0
        info.setUEType(UEType);//0
        info.setAPN(APN);//1
        info.setIPAddress(IPAddress);//1
        info.setRSRP(RSRP);//1
        info.setRSSI(RSSI);//0
        info.setPCI(PCI);//1
        info.setCellID(CellID);//1
        info.setTXPower(TXPower);//0
        info.setEARFCN(EARFCN);//0
        info.setPositionCoordinates(PositionCoordinates);//1
        if (ReportType != 1 && isDrag >= 2)
            info.setPositionCoordinates(PositionCoordinates2);//1
        info.setAltitude(Altitude);//0
        info.setModelVersion(ModelVersion);//0
        info.setSNR(SNR + "");//1
        info.setTimeStamp(System.currentTimeMillis());//0
        info.setReportType(ReportType);//0
        info.setPositionRemark(autoAddress + mEtNote.getText().toString());//1
        if (ReportType != 1 && isDrag >= 2)
            info.setPositionRemark(mTvAddress.getText() + mEtNote.getText().toString());//1
        info.setPingReturnedValue(PingReturnedValue.toString());
        //0必选 1非必
        if (CFUN == 0) {
            Toast.makeText(MainActivity.this, "NB模组未能使用，将不上报，具体请见历史记录", Toast.LENGTH_SHORT).show();
            info.setIsSucceed(2);
            info.save();
        } else {
//        info.save();
            JSONObject param = new JSONObject();
            try {
                param.put("IMSI", IMSI);//0
                param.put("IMEI", IMEI);//0
                param.put("UEType", UEType);
                if (!StringUtil.isNull(APN))
                    param.put("APN", APN);//1
                param.put("IPAddress", IPAddress);//1
                param.put("RSRP", RSRP);//1
                if (RSSI != 0)
                    param.put("RSSI", RSSI);//0
                if (!StringUtil.isNull(PCI))
                    param.put("PCI", PCI);//1
                if (!StringUtil.isNull(CellID))
                    param.put("CellID", CellID);//1
                param.put("TXPower", TXPower);//0
                param.put("EARFCN", EARFCN);//0
//            PositionCoordinates = "+23.03123,+113.75123";
                if (ReportType == 1) {
                    if (!StringUtil.isNull(PositionCoordinates))
                        param.put("PositionCoordinates", PositionCoordinates);//1
                } else {
                    if (isDrag >= 2) {
                        if (!StringUtil.isNull(PositionCoordinates2))
                            param.put("PositionCoordinates", PositionCoordinates2);//1
                    } else {
                        if (!StringUtil.isNull(PositionCoordinates))
                            param.put("PositionCoordinates", PositionCoordinates);
                    }
                }
                param.put("Altitude", Altitude);//0
                param.put("ModelVersion", ModelVersion);//0
//                if (!StringUtil.isNull(SNR))
                param.put("SNR", SNR + "");//1
                param.put("TimeStamp", System.currentTimeMillis());//0
                param.put("ReportType", ReportType);//0
                if (ReportType == 1) {
                    param.put("PositionRemark", autoAddress + mEtNote.getText().toString());//1
                } else {
                    if (isDrag >= 2) {
                        param.put("PositionRemark", mTvAddress.getText() + mEtNote.getText().toString());//1
                    } else {
                        param.put("PositionRemark", autoAddress + mEtNote.getText().toString());//1
                    }
                }
                if (ReportType == 2)
                    param.put("PingReturnedValue", PingReturnedValue);//1
                JSONArray array = new JSONArray();
                array.put(param);
                post.sumit(array, info);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }


    public void updata() {
        OkHttpUtils
                .get()
                .url("http://14.116.252.204:9080/MsgCallbackGW/apk-version-update/get-version-info")
                .build()
                .execute(new MyCallBack(new UpdateInfo()) {

                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(Object response) {
                        UpdateInfo info = (UpdateInfo) response;
                        // ToastUtil.ToastUtil(MainActivity.this, info.getMessage());
                        if (info.getOptResult().equals("0")) {
                            {
                                versionCode = info.getVersionCode();
                                ApKURL = info.getVersionPath();
                                version_description = info.getVersionDesc();
                                updateUtil = new UpdateUtil(MainActivity.this, ApKURL, version_description);
                                try {
                                    if (Double.parseDouble(versionCode) > Double.parseDouble(updateUtil.getVersionName())) {
                                        if (Build.VERSION.SDK_INT >= M) {
                                            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                                    != PackageManager.PERMISSION_GRANTED) {
                                                //申请WRITE_EXTERNAL_STORAGE权限
                                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                        1);
                                            } else {
                                                updateUtil.showUpdateDialog();
                                            }
                                        } else {
                                            updateUtil.showUpdateDialog();

                                        }
                                    } else {
                                        //ToastUtil.ToastUtil(MainActivity.this,"已经是最新版了");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                        }
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                updateUtil.showUpdateDialog();
            } else {
                // Permission Denied
                Toast.makeText(MainActivity.this, "授权失败，无法更新", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == 1001) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                getLocation();
            } else {
                // Permission Denied
                Toast.makeText(MainActivity.this, "授权定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    public void showAboutDialog() {
        final AlertDialog builder = new AlertDialog.Builder(this).create();
        builder.show();
        builder.getWindow().setContentView(R.layout.about_dialog);
        builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        //一定得在show完dialog后来set属性
        WindowManager m = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams lp = builder.getWindow().getAttributes();
        lp.width = (int) (d.getWidth() * 0.9);
        builder.getWindow().setAttributes(lp);
        PackageManager packageManager = MainActivity.this.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(MainActivity.this.getPackageName(), 0);
            String version = packInfo.versionName;
            TextView mTvVersion = (TextView) builder.getWindow().findViewById(R.id.mTvVersion);
            mTvVersion.setText("版本号：" + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        builder.setCancelable(true);
        RadioGroup mRgTime2 = (RadioGroup) builder.getWindow().findViewById(R.id.mRg2Time);
        RadioButton tb = (RadioButton) builder.getWindow().findViewById(lastId);
        tb.toggle();
        mRgTime2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                if (state != -1 && id != lastId) {
                    RadioButton tb = (RadioButton) builder.getWindow().findViewById(lastId);
                    tb.toggle();
                    Toast.makeText(MainActivity.this, "请稍后再点击！", Toast.LENGTH_SHORT).show();
                } else {
                    if (lastId != id)
                        if (MyApp.driver.isConnected()) {
                            lastId = id;
                            state = 0;
                            isSetCYCLE = true;
                            switch (id) {
                                case R.id.mRb2Time1:
                                    cycle_time = 10;
                                    break;
                                case R.id.mRb2Time2:
                                    cycle_time = 30;
                                    break;
                                case R.id.mRb2Time3:
                                    cycle_time = 60;
                                    break;
                                case R.id.mRb2Time4:
                                    cycle_time = 300;
                                    break;
                                case R.id.mRb2Time5:
                                    cycle_time = 600;
                                    break;
                            }
                            Toast.makeText(MainActivity.this, "正在设置", Toast.LENGTH_SHORT).show();
                            if (isAuto) {//若处于自动上报状态，暂停线程进行手动上报，完毕以后再进行自动上报
                                Timehandler.removeCallbacks(TimeRunnable);
                                write(Connect);
                                Timehandler.postDelayed(TimeRunnable, update_time);
                            } else {
                                write(Connect);
                            }

                        } else {
                            Toast.makeText(MainActivity.this, "正在重连", Toast.LENGTH_SHORT).show();
                            open();
                        }
                    builder.dismiss();
                }
            }
        });

        LinearLayout dialog_ok = (LinearLayout) builder.getWindow().findViewById(R.id.mLyOk);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                builder.dismiss();
            }
        });
    }

    public void pingDialog(String str) {
        final Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle("Ping延时结果")
                .setMessage(str)
                .setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0,
                                                int arg1) {
                                arg0.dismiss();
                            }
                        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public void cycleDialog(String str, final int id) {
        final Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle("要设置NS101上报间隔为" + str + "吗？")
//                .setMessage(str)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int i) {
//                        mRgTime2.check(lastId);
                        RadioButton tb = (RadioButton) findViewById(lastId);
                        tb.toggle();
                        arg0.dismiss();
                    }
                })
                .setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0,
                                                int arg1) {
                                if (state != -1) {
                                    RadioButton tb = (RadioButton) findViewById(lastId);
                                    tb.toggle();
                                    Toast.makeText(MainActivity.this, "请稍后再点击！", Toast.LENGTH_SHORT).show();
                                    arg0.dismiss();
                                } else {

                                    arg0.dismiss();
                                }
                            }
                        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public void setInfo(ServiceInfo info) {
        lastInfo = info;
        mLyDetail.setVisibility(View.VISIBLE);
    }

    public void showDetailDialog() {
        final AlertDialog builder = new AlertDialog.Builder(MainActivity.this).create();
        builder.show();
        builder.getWindow().setContentView(R.layout.detail_dialog);
        builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        //一定得在show完dialog后来set属性
        WindowManager m = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams lp = builder.getWindow().getAttributes();
        lp.width = (int) (d.getWidth() * 0.9);
        builder.getWindow().setAttributes(lp);

        builder.setCancelable(true);
        TextView mTvImei = (TextView) builder.getWindow().findViewById(R.id.mTvImei);
        TextView mTvImsi = (TextView) builder.getWindow().findViewById(R.id.mTvImsi);
        TextView mTvUEType = (TextView) builder.getWindow().findViewById(R.id.mTvUEType);
        TextView mTvAPN = (TextView) builder.getWindow().findViewById(R.id.mTvAPN);
        TextView mTvRSRP = (TextView) builder.getWindow().findViewById(R.id.mTvRSRP);
        TextView mTvRSSI = (TextView) builder.getWindow().findViewById(R.id.mTvRSSI);
        TextView mTvPCI = (TextView) builder.getWindow().findViewById(R.id.mTvPCI);
        TextView mTvCellID = (TextView) builder.getWindow().findViewById(R.id.mTvCellID);
        TextView mTvTXPower = (TextView) builder.getWindow().findViewById(R.id.mTvTXPower);
        TextView mTvEARFCN = (TextView) builder.getWindow().findViewById(R.id.mTvEARFCN);
        TextView mTvAltitude = (TextView) builder.getWindow().findViewById(R.id.mTvAltitude);
        TextView mTvModelVersion = (TextView) builder.getWindow().findViewById(R.id.mTvModelVersion);
        TextView mTvSNR = (TextView) builder.getWindow().findViewById(R.id.mTvSNR);
        TextView mTvIPAddress = (TextView) builder.getWindow().findViewById(R.id.mTvIPAddress);
        TextView mTvReportType = (TextView) builder.getWindow().findViewById(R.id.mTvReportType);
        TextView mTvPositionRemark = (TextView) builder.getWindow().findViewById(R.id.mTvPositionRemark);

        TextView mTvLat = (TextView) builder.getWindow().findViewById(R.id.mTvLat);
        TextView mTvLon = (TextView) builder.getWindow().findViewById(R.id.mTvLon);
        mTvImei.setText("IMEI:" + lastInfo.getIMEI());
        mTvImsi.setText("IMSI:" + lastInfo.getIMSI());
        mTvUEType.setText("UEType:" + lastInfo.getUEType());
        mTvAPN.setText("APN:" + lastInfo.getAPN());
        mTvRSRP.setText("RSRP:" + lastInfo.getRSRP());
        mTvRSSI.setText("RSSI:" + lastInfo.getRSSI());
        mTvPCI.setText("PCI:" + lastInfo.getPCI());
        mTvCellID.setText("CellID:" + lastInfo.getCellID());
        mTvTXPower.setText("TXPower:" + lastInfo.getTXPower());
        mTvEARFCN.setText("EARFCN:" + lastInfo.getEARFCN());
        mTvAltitude.setText("Altitude:" + lastInfo.getAltitude());
        mTvModelVersion.setText("ModelVersion:" + lastInfo.getModelVersion());
        mTvSNR.setText("SNR:" + lastInfo.getSNR());
        mTvIPAddress.setText("IPAddress:" + lastInfo.getIPAddress());
        mTvReportType.setText("ReportType:" + lastInfo.getReportType());
        mTvPositionRemark.setText("PositionRemark:" + lastInfo.getPositionRemark());

        try {
            String str = lastInfo.getPositionCoordinates();
            str = str.replace("+", "");
            mTvLon.setText("经度:" + str.split(",")[1]);
            mTvLat.setText("纬度:" + str.split(",")[0]);
        } catch (Exception ex) {
            mTvLon.setText("经度:0");
            mTvLat.setText("纬度:0");
        }
        LinearLayout dialog_ok = (LinearLayout) builder.getWindow().findViewById(R.id.mLyOk);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                builder.dismiss();
            }
        });
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                double mLatitude;
                double mLongtitude;
                //用于记录定位的位置经纬度
                mLatitude = location.getLatitude();
                mLongtitude = location.getLongitude();
                LatLng ll = new LatLng(mLatitude, mLongtitude);
                if (isGetLocation) {
                    MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
                    mBaiduMap.animateMapStatus(update);
//                    LatLng latLng = mBaiduMap.getMapStatus().target;
                    latlngToAddress(ll);
                    isGetLocation = false;
                }
                String i = location.getLocTypeDescription();
//                Toast.makeText(MainActivity.this, i, Toast.LENGTH_SHORT).show();
                DecimalFormat df = new DecimalFormat("######0.00000");
                PositionCoordinates = "+" + location.getLatitude() + ",+" + location.getLongitude();
                latlngToAddress2(ll);
                GPS = "\r\nGPSINFO:" + location.getLatitude() + "|N|" + location.getLongitude() + "|E|" + location.getAltitude() + "\r\n";
                Altitude = String.valueOf(location.getAltitude());
                if (Altitude.equals("4.9E-324"))
                    Altitude = "0";
//                mLocationClient.stop();
            } else {
                Toast.makeText(MainActivity.this, "定位失败！", Toast.LENGTH_SHORT).show();
//                mLocationClient.stop();
            }
        }

    };
    BaiduMap.OnMapStatusChangeListener onMapStatusChangeListener = new BaiduMap.OnMapStatusChangeListener() {
        LatLng startLng, finishLng;

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {
            startLng = mapStatus.target;
        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
            startLng = mapStatus.target;
        }

        @Override
        public void onMapStatusChangeFinish(MapStatus mapStatus) {
            // 滑动搜索
            finishLng = mapStatus.target;
            if (startLng.latitude != finishLng.latitude
                    || startLng.longitude != finishLng.longitude) {
                Projection ject = mBaiduMap.getProjection();
                Point startPoint = ject.toScreenLocation(startLng);
                Point finishPoint = ject.toScreenLocation(finishLng);
                isDrag++;
                PositionCoordinates2 = "+" + finishLng.latitude + ",+" + finishLng.longitude;
                latlngToAddress(finishLng);
            }
        }

        @Override
        public void onMapStatusChange(MapStatus mapStatus) {
        }
    };

    private void latlngToAddress(LatLng latlng) {

        // 设置反地理经纬度坐标,请求位置时,需要一个经纬度
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latlng));


        //设置地址或经纬度反编译后的监听,这里有两个回调方法,

        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            //经纬度转换成地址

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(MainActivity.this, "找不到该地址!", Toast.LENGTH_SHORT).show();
                }
//                Toast.makeText(MainActivity.this, result.getSematicDescription(), Toast.LENGTH_SHORT).show();

                mTvAddress.setText(result.getAddress());
            }


            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                // 详细地址转换在经纬度

                String address = result.getAddress();

            }
        });
    }

    private void latlngToAddress2(LatLng latlng) {

        // 设置反地理经纬度坐标,请求位置时,需要一个经纬度
        geoCoder2.reverseGeoCode(new ReverseGeoCodeOption().location(latlng));


        //设置地址或经纬度反编译后的监听,这里有两个回调方法,

        geoCoder2.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            //经纬度转换成地址

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(MainActivity.this, "找不到该地址!", Toast.LENGTH_SHORT).show();
                }
//                Toast.makeText(MainActivity.this, result.getSematicDescription(), Toast.LENGTH_SHORT).show();

                autoAddress = result.getAddress();
            }


            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                // 详细地址转换在经纬度

                String address = result.getAddress();

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.unRegisterLocationListener(mListener); //注销掉监听
        mLocationClient.stop(); //停止定位
        mMapView.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
}
